package 网络编程;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Receiver implements Runnable{
    private int fromPort;
    private String fromName;
    DatagramSocket socket=null;

    public Receiver(int fromPort, String fromName) {
        this.fromPort = fromPort;
        this.fromName = fromName;
        try{
            socket=new DatagramSocket(fromPort);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
        try {
                byte[] bus = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bus, 0, bus.length);
                socket.receive(packet);
            String str=new String(packet.getData(), 0, packet.getLength());
            System.out.println(fromName+":"+str);
            if (str.equals("byte")) {
                break;
            }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
